package com.oromwin.repos.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposConfig;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.http.handler.ExitHandler;
import com.sun.net.httpserver.HttpServer;

public class ReposHttpServer extends Thread {
    private static Log log = Logger.getLog(ReposHttpServer.class);
    private static int waitSeconds = 5000;
    private static boolean hasStopped = false;
    private final static int port = ReposConfig.getInstance().getReposHttpServerPort();
    
    private HttpServer server = null;
    private ExitHandler exitHandler = null;
    
    
    public ReposHttpServer() throws ReposException {
        try {
            this.server = HttpServer.create(new InetSocketAddress(port), port);
        } catch (IOException e) {
            throw ReposException.create(log, e.getMessage());
        }
        exitHandler = new ExitHandler();
        server.createContext("/exit", exitHandler);
        this.server.setExecutor(Executors.newFixedThreadPool(10));
    }

    public void run() {
        this.server.start();
        if (log.isInfoEnabled()) log.info("HttpServer has started.");
        while (exitHandler.isRunning()) {
            try {
                Thread.sleep(waitSeconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.server.stop(0);
        hasStopped = true;
        if (log.isInfoEnabled()) log.info("HttpServer has stopped");
    }

    @Override
    public void finalize() {
        if (log.isInfoEnabled()) log.info("Shutting down httpServer.");
    }

    public boolean hasStopped() {
        return hasStopped;
    }
}
